 package com.zhangqiang.git.opc.opclink.task;

import com.zhangqiang.git.opc.opclink.config.OpcConfig;
import com.zhangqiang.git.opc.opclink.model.Result;
import com.zhangqiang.git.opc.opclink.model.ResultCode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

 /**
  * OPC 连接配置
  */
@EnableScheduling
@Configuration
public class OpcTask {

    private static final Logger log = LoggerFactory.getLogger(OpcTask.class);

    // OPC标签
    private static ConcurrentHashMap<String,String> OPC_LABELS = new ConcurrentHashMap<>();
    // OPC标签值
    private static ConcurrentHashMap<String,String> OPC_LABELS_DATA = new ConcurrentHashMap<>();

    @Resource
    OpcConfig opcConfig;


    /**
     * 初始化OPC接入
     * @return
     */
    @PostConstruct
    private void init() {
        opcConfig.initOpcClient();
        initOpcLabels();
        initOpcLabelsData();
    }






     /**
      * OPC标签信息初始化
      * 放入缓存
      */
    public void initOpcLabels(){
        OPC_LABELS.clear();
        // to do
        OPC_LABELS.put("标签名称","标签标识");
    }

     /**
      * OPC标签值数据初始化
      */
    public void initOpcLabelsData(){
        OPC_LABELS_DATA.clear();
        OPC_LABELS_DATA.put("标签标识","标签值");
    }


    /**
     * 定时获取OPC服务的标签数据
     */
    @Scheduled(cron = "${opc.task}")
    private void readOPCData(){
        log.info("======================== 任务开始");
        // 设备批量标签值读取
        Result result = opcConfig.readItemsValues(OPC_LABELS.keySet().toArray(new String[OPC_LABELS.keySet().size()]));
        if(!ResultCode.SUCCESS.getValue().equals(result.getCode()))return;
        Map<String, Object> item_values = (Map<String, Object>)result.getData();
        // 标签值录入登记
        item_values.forEach((label,d)->{

            String opcValue = String.valueOf(d);

            OPC_LABELS_DATA.put(label,opcValue);

            log.info(label+"值：" + opcValue);
            // to do 插入数据库

        });
        log.info("======================== 任务结束");
    }

}
